package com.zeny.express.framework.scheduler.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.zeny.express.framework.scheduler.dao.SchedulerInfoEntityDao;
import com.zeny.express.framework.scheduler.dao.SchedulerLogEntityDao;
import com.zeny.express.framework.scheduler.entity.SchedulerInfoEntity;
import com.zeny.express.framework.scheduler.entity.SchedulerLogEntity;
import com.zeny.express.framework.scheduler.service.SchedulerLogService;
import com.zeny.express.framework.shared.domain.Constants;

@Service
public class SchedulerLogServiceImpl implements SchedulerLogService {

	@Autowired
	private SchedulerInfoEntityDao schedulerInfoEntityDao;
	
	@Autowired
	private SchedulerLogEntityDao schedulerLogEntityDao;
	
	private List<SchedulerInfoEntity> schedulerInfos;
	
	private Map<String, SchedulerInfoEntity> jobIdMap;

	@Override
	public void storeSchedulerInfos(String schedulerName) {

		SchedulerInfoEntity entity = new SchedulerInfoEntity();
		entity.setSchedulerName(schedulerName);
		entity.setActive(Constants.YES);
		
		schedulerInfos = schedulerInfoEntityDao.selectSchedulerInfos(entity);
		jobIdMap = Maps.uniqueIndex(schedulerInfos, new Function<SchedulerInfoEntity, String>() {
			@Override
			public String apply(SchedulerInfoEntity entity) {
				return entity.getJobId();
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<SchedulerInfoEntity> querySchedulerInfos(String jobName) {
		Predicate p = new BeanPropertyValueEqualsPredicate("jobName", jobName);
		return CollectionUtils.select(schedulerInfos, p);
	}

	@Override
	public SchedulerInfoEntity querySchedulerInfo(String jobId) {
		return jobIdMap.get(jobId);
	}

	@Override
	public void beginSchedulerLog(SchedulerLogEntity schedulerLog) {
		schedulerLogEntityDao.insert(schedulerLog);
		
		SchedulerInfoEntity info = querySchedulerInfo(schedulerLog.getJobId());
		info.setBeginTime(schedulerLog.getBeginTime());
		schedulerInfoEntityDao.updateBeginTime(info);
	}

	@Override
	public void endSchedulerLog(SchedulerLogEntity schedulerLog) {
		schedulerLogEntityDao.update(schedulerLog);
		
		SchedulerInfoEntity info = querySchedulerInfo(schedulerLog.getJobId());
		info.setEndTime(schedulerLog.getEndTime());
		info.setParam(schedulerLog.getParam());
		schedulerInfoEntityDao.updateEndTime(info);
	}

}
